package com.MasterDevelopers.MessageMaster;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class TextEdit extends Activity {
	private EditText mTitleText;
	private EditText mBodyText;
	private EditText mPhoneNumberText;
	private Long mRowId;
	private DbAdapter mDbHelper;
	private static final String TAG = "MessageMaster";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDbHelper = new DbAdapter(this);
		mDbHelper.open();

		setContentView(R.layout.text_edit);
		mTitleText = (EditText) findViewById(R.id.title);
		mBodyText = (EditText) findViewById(R.id.body);
		mPhoneNumberText = (EditText) findViewById(R.id.phoneNumber);

		Button confirmButton = (Button) findViewById(R.id.confirm);

		mRowId = savedInstanceState != null ? savedInstanceState
				.getLong(DbAdapter.KEY_ROWID) : null;
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();
			mRowId = extras != null ? extras.getLong(DbAdapter.KEY_ROWID)
					: null;
		}

		populateFields();

		confirmButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				setResult(RESULT_OK);
				finish();
			}

		});
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (mRowId != null) {
			outState.putLong(DbAdapter.KEY_ROWID, mRowId);
		}
	}

	@Override
	protected void onPause() {
		Log.i("MessageMaster", "On Pause");
		super.onPause();
		saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}

	private void populateFields() {
		if (mRowId != null) {
			Message m = mDbHelper.fetchTextMessage(mRowId);
			if (m == null){
				Log.e(TAG, "Cannot find message for id: " + mRowId.toString());
				return;
			}

			mTitleText.setText(m.getTitle());
			mBodyText.setText(m.getBody());
			mPhoneNumberText.setText(m.getAddresses().getAddress());
		}
	}

	private void saveState() {
		String title = mTitleText.getText().toString();
		String body = mBodyText.getText().toString();
		String phoneNumber = mPhoneNumberText.getText().toString();

		if (mRowId == null) {
			long id = mDbHelper.createTextMessage(title, phoneNumber, body);
			if (id > 0) {
				mRowId = id;
			}
		} else {
			mDbHelper.updateTextMessage(mRowId, title, phoneNumber, body);
		}
	}
}